package com.cygsunri.coreExtend.service;

import com.cygsunri.cache.RedisCacheService;
import com.cygsunri.event.entity.EventInfo;
import com.cygsunri.event.service.EventService;
import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


/**
 * 缓存初始化
 */
@Slf4j
@Component
public class CacheRunner implements InitializingBean {

    @Resource
    private List<CacheManager> cacheManagers;

    @Autowired
    private RedisCacheService redisCacheService;

    @Autowired
    private EventService eventService;

    /**
     * 开启缓存
     */
    @Override
    public void afterPropertiesSet() {
        //开启测点缓存到redis
        redisCacheService.cacheToRedis();
        //开启测点缓存到GuavaCache
        cacheYxInfo();
    }

    @Bean
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        cacheManager.setCaffeine(Caffeine.newBuilder());

        List<String> guavaCacheNames = new ArrayList<>();
        guavaCacheNames.add("YxInfoMapping");
        cacheManager.setCacheNames(guavaCacheNames);

        return cacheManager;
    }

    /**
     * 缓存遥信信息
     */
    private void cacheYxInfo() {
        log.info("开始Guava缓存=================================================");
        long a = System.currentTimeMillis();

        for (CacheManager c : cacheManagers) {
            if (c.getCacheNames().contains("YxInfoMapping")) {
                Cache cache = c.getCache("YxInfoMapping");
                yxInfoMapping(cache);
            }
        }
        log.info("Guava缓存耗时：{}ms", System.currentTimeMillis() - a);
    }

    private void yxInfoMapping(Cache cache) {
        List<EventInfo> eventInfoList = eventService.getYxInfo();
        eventInfoList.forEach(eventInfo -> {
            cache.put(eventInfo.getMeasurementID(), eventInfo);
        });
    }
}
